package com.java.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.util.DigestUtils;

public class MyTools {

	public static String getUUID() {
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		return uuid;
	}

	public static boolean isEmpty(Object pObj) {
		if (pObj == null)
			return true;
		if (pObj == "" || pObj.equals("null"))
			return true;
		if (pObj instanceof String) {
			if (((String) pObj).length() == 0) {
				return true;
			}
		} else if (pObj instanceof Collection) {
			if (((Collection<?>) pObj).size() == 0) {
				return true;
			}
		} else if (pObj instanceof Map) {
			if (((Map<?, ?>) pObj).size() == 0) {
				return true;
			}
		}
		return false;
	}
	
	public static String getMd5(String string) {
		return DigestUtils.md5DigestAsHex(string.getBytes());
	}
	
	public static boolean md5Match(String def, String target) {
		String hex = DigestUtils.md5DigestAsHex(def.getBytes());
		return hex.equals(target);
	}

	public static String getDateStr(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	public static Date getDate(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sdf.parse(date);
		} catch (ParseException e) {
			return null;
		}
	}

	public static LocalDate getLocalDate(String date) {
		try {
			return LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		} catch (Exception e) {
			return null;
		}
	}

	public static List<String> last7Date() {
		List<String> list = new ArrayList<String>();
		LocalDate before7 = LocalDate.now().minusDays(6);
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		for (int i = 0; i < 7; i++) {
			list.add(before7.format(formatter));
			before7 = before7.plusDays(1);
		}
		return list;
	}

	public static List<String> getDatesBetween(LocalDate startDate, LocalDate endDate) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		List<String> dates = new ArrayList<>();
		long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
		for (int i = 0; i <= numOfDaysBetween; i++) {
			LocalDate date = startDate.plusDays(i);
			dates.add(date.format(formatter));
		}
		return dates;
	}
}
